package com.frank.auth.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.frank.auth.common.enums.RedisKeyPrefixEnum;
import com.frank.auth.domain.bo.AuthPermissionBo;
import com.frank.auth.domain.convert.AuthPermissionBoConvert;
import com.frank.auth.domain.redis.RedisUtil;
import com.frank.auth.domain.service.PermissionDomainService;
import com.frank.auth.infra.basic.entity.AuthPermission;
import com.frank.auth.infra.basic.service.AuthPermissionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @author Frank Zou
 * @version v0.0.1
 * @date 2024/2/13
 * @description
 */
@Service
public class PermissionDomainServiceImpl implements PermissionDomainService {

    private final AuthPermissionService authPermissionService;

    private final RedisUtil redisUtil;

    public PermissionDomainServiceImpl(AuthPermissionService authPermissionService,
                                       RedisUtil redisUtil) {
        this.authPermissionService = authPermissionService;
        this.redisUtil = redisUtil;
    }

    @Override
    public Boolean addPermission(AuthPermissionBo authPermissionBo) {
        AuthPermission authPermission = AuthPermissionBoConvert.INSTANCE.convertBoToEntity(authPermissionBo);
        return authPermissionService.save(authPermission);
    }

    @Override
    public Boolean updatePermission(AuthPermissionBo authPermissionBo) {
        AuthPermission authPermission = AuthPermissionBoConvert.INSTANCE.convertBoToEntity(authPermissionBo);
        return authPermissionService.updateById(authPermission);
    }

    @Override
    public Boolean deletePermission(Long id) {
        return authPermissionService.removeById(id);
    }

    @Override
    public List<String> getPermission(String username) {
        String permissionKey = redisUtil.buildKey(RedisKeyPrefixEnum.PERMISSION_KEY.getKey(), username);
        String permissions = redisUtil.get(permissionKey);
        if (StringUtils.isBlank(permissions)){
            return Collections.emptyList();
        }
        return JSON.parseArray(permissions, String.class);
    }
}
